<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\UserTools;
use App\Admin\Repositories\User;
use App\Admin\RowActions\ResetUserTest;
use App\Models\Answer;
use App\Models\Test;
use App\Models\Unit;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Dcat\EasyExcel\Excel;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        // ['unit', 'test'] 取消 with test
        return Grid::make(User::with(['unit']), function (Grid $grid) {
            $grid->disableBatchDelete();

            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('username');
            $grid->column('unit.name', trans('user.fields.unit'))->sortable();
            $grid->column('room');

            // $grid->column('max_score')->display(function () {
            //     return $this->test->max('test_score');
            // });
            //
            // $grid->column('test')->display(function (Collection $tests) {
            //     $score = $tests->map(function (Test $test, $index) {
            //         return '<li>第 ' . ($index + 1) . ' 次考试成绩：' . $test->test_score . '</li>';
            //     })->join('');
            //
            //     return "<ul>$score</ul>";
            // });

            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('name');
                $filter->like('username');
                $filter->equal('unit_id')->select(Unit::query()->pluck('name', 'id'));
            });

            // 行操作按钮
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new ResetUserTest(User::class));
            });

            // 工具栏
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append(new UserTools());
            });

            // 导出
            $grid->export([
                'id' => 'ID',
                'name' => '姓名',
                'username' => '用户名',
                'unit' => '单位',
                // 'score' => '最高分',
                // 'score_1' => '第1次考试成绩',
                // 'score_2' => '第2次考试成绩',
                // 'score_3' => '第3次考试成绩',
            ])->rows(function (array $rows) {
                foreach ($rows as $index => &$row) {
                    // $maxScore = max(
                    //     $row['test'][0]['test_score'] ?? 0,
                    //     $row['test'][1]['test_score'] ?? 0,
                    //     $row['test'][2]['test_score'] ?? 0
                    // );
                    $row = [
                        'id' => $row['id'],
                        'name' => $row['name'],
                        'username' => $row['username'],
                        'unit' => $row['unit']['name'],
                        // 'score' => $maxScore,
                        // 'score_1' => $row['test'][0]['test_score'] ?? 0,
                        // 'score_2' => $row['test'][1]['test_score'] ?? 0,
                        // 'score_3' => $row['test'][2]['test_score'] ?? 0,
                    ];
                }

                return $rows;
            })->filename('用户-' . date('Ymd-His'));
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, User::with(['unit']), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('username');
            $show->field('unit.name', trans('user.fields.unit'));
            $show->field('room');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new User(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->text('username')->required()->rules('unique:users,username,' . $form->model()->id);

            // 编辑时密码非必填项
            if ($form->isEditing()) {
                $form->text('password')->help('不修改密码时请留空！');
            } else {
                $form->text('password')->required();
            }

            $form->select('unit_id')->options(Unit::query()->pluck('name', 'id'));
            $form->text('room');

            $form->hidden('email');
            $form->display('created_at');
            $form->display('updated_at');
        })->saving(function (Form $form) {
            // 修改密码时要加密，不修改时要删除传入的空值
            if ($password = $form->input('password')) {
                $form->input('password', Hash::make($password));
            } else {
                $form->deleteInput('password');
            }
            $form->input('unit_id', (int) $form->input('unit_id'));
            $form->input('room', (string) $form->input('room'));
            $form->input('email', $form->input('username') . '@example.org');
        })->saved(function (Form $form) {
            // 统计各单位用户数
            Unit::refreshUserCount();
        })->deleted(function (Form $form) {
            $userId = $form->getKey();

            // 删除考试与答题记录
            Test::query()->where('user_id', $userId)->delete();
            Answer::query()->where('user_id', $userId)->delete();

            // 统计各单位用户数
            Unit::refreshUserCount();
        });
    }

    /**
     * 导入用户
     *
     * @param Request $request
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function import(Request $request)
    {
        set_time_limit(0);

        // 直接读取前端上传的文件
        try {
            $users = Excel::import($request->file('_file_'))->first()->toArray();
        } catch (\Exception $e) {
            return \Admin::json()->error('无法读取文件！');
        }

        // 单位
        $units = Unit::query()->pluck('name', 'id');
        $createdAt = now();

        $users = collect($users)->map(function ($user) use (&$units, $createdAt) {
            $unitId = $units->search($user['单位']);

            // 单位不存在时创建
            if (! $unitId) {
                $unitId = Unit::query()->insertGetId([
                    'name' => $user['单位'],
                    'order' => Unit::query()->max('order') + 1,
                    'created_at' => now(),
                ]);
                $units = $units->put($unitId, $user['单位']);
            }

            return [
                'name' => $user['姓名'],
                'username' => $user['登录账号'],
                'unit_id' => $unitId,
                'room' => $user['处室'],
                'email' => $user['登录账号'] . '@example.org',
                'password' => Hash::make($user['密码']),
                'created_at' => $createdAt,
            ];
        })->unique('username')->toArray();

        try {
            \App\Models\User::query()->insertOrIgnore($users);

            // 统计各单位用户数
            Unit::refreshUserCount();

            return \Admin::json()->success('导入成功！');
        } catch (\Exception $e) {
            return \Admin::json()->error('导入失败！');
        }
    }
}
